package com.springcloud.alibabanacosconfig.mq.component;

import com.springcloud.alibabanacosconfig.mq.listener.UserOrderListener;
import com.springcloud.alibabanacosconfig.mq.service.ConcurrencyService;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @version V1.0
 * @Author 宋聚智
 * @Date 2019/10/22 18:11
 * @description  抢单模型
 * @Modify By：
 * @ModifyTime： 2019/10/22
 * @Modify marker：
 **/
@Configuration
public class UserOrderConfig {
    @Autowired
    Environment env;

    @Autowired
    private CachingConnectionFactory connectionFactory;


    @Autowired
    UserOrderListener userOrderListener;


    @Bean(name="userOrderQueue")
    public Queue userOrderQueue(){
        return  new Queue(env.getProperty("user.order.queue.name"),true);
    }

    @Bean
    public TopicExchange userOrderExchange(){
        return new TopicExchange(env.getProperty("user.order.exchange.name"),true,false);
    }

    @Bean
    public Binding userOrderBinding(){
        return BindingBuilder.bind(userOrderQueue()).to(userOrderExchange()).with(env.getProperty("user.order.routing.key.name"));
    }
    // SimpleMessageListenerContainer 消息侦听器容器
    // setMessageListener()方法为指定的侦听器创建并发MessageConsumers
    @Bean
    public SimpleMessageListenerContainer listenerContainerUserOrder(@Qualifier("userOrderQueue") Queue userOrderQueue){
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setMessageConverter(new Jackson2JsonMessageConverter());
        //处理并发配置
        container.setConcurrency(env.getProperty("spring.rabbitmq.listener.simple.concurrency",String.class));
        container.setMaxConcurrentConsumers(env.getProperty("spring.rabbitmq.listener.simple.max-concurrency",Integer.class));
        container.setPrefetchCount(env.getProperty("spring.rabbitmq.listener.simple.prefetch",Integer.class));
        //处理消息确认配置
        container.setQueues(userOrderQueue);
        container.setMessageListener(userOrderListener);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //手动
        return container;
        // 明日处理： nacos 配置消息修改及添加
    }

}

